package com.zhao.wechat.service;


import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateUnit;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson2.JSON;
import com.zhao.wechat.config.WechatConfig;

import com.zhao.wechat.config.WechatTemplate;
import com.zhao.wechat.config.WechatTemplateList;
import com.zhao.wechat.domain.*;
import com.zhao.wechat.remote.BaiduWeatherRemoteClient;
import com.zhao.wechat.remote.TianDataRemoteClient;
import com.zhao.wechat.remote.param.BaiduWeatherParam;
import com.zhao.wechat.remote.param.TianXinParam;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.mp.api.WxMpInMemoryConfigStorage;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.api.impl.WxMpServiceImpl;
import me.chanjar.weixin.mp.bean.template.WxMpTemplateData;
import me.chanjar.weixin.mp.bean.template.WxMpTemplateMessage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;


import java.time.format.DateTimeFormatter;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Objects;

@Slf4j
@Service
public class PushDailyWechatImpl implements PushDailyWechat{
	@Autowired
	private UserInfoService userInfoService;
	@Autowired
	private BaiduWeatherRemoteClient baiduWeatherRemoteClient;
	@Autowired
	private TianDataRemoteClient tianDataRemoteClient;
	/** 微信配置类 **/
	@Autowired
	private WechatConfig wechatConfig;
	/** 模板列表**/
	@Autowired
	private WechatTemplateList wechatTemplateList;

	/** ak **/
	@Value("${baidu.ak}")
	private String ak;

	/** key **/
	@Value("${tianxin.key}")
	private String key;


	/**
	 * 给不同的用户推送消息
	 */
	@Override
	public void pushWechat() throws WxErrorException {
		// 获取用户列表
		List<UserInfo> userInfoList = userInfoService.listUserInfo();
		if (!CollectionUtils.isEmpty(userInfoList)){
			// 根据用户的type类型和模板type进行匹配
			for (UserInfo userInfo : userInfoList) {
				for (WechatTemplate template : wechatTemplateList.getTemplatelist()) {
					if (userInfo.getType().equals(template.getType())){
						this.wechatData(userInfo.getWechatId(), template.getTemplateId(),userInfo);
					}
				}
			}
		}
	}

	/**
	 * 封装微信数据
	 * @param wechatId
	 * @param templateId
	 */
	private void wechatData(String wechatId,String templateId,UserInfo userInfo) throws WxErrorException {
		// 创建配置信息
		WxMpInMemoryConfigStorage wxStorage = new WxMpInMemoryConfigStorage();
		wxStorage.setAppId(wechatConfig.getAppId());
		wxStorage.setSecret(wechatConfig.getAppSecret());
		WxMpService wxMpService = new WxMpServiceImpl();
		wxMpService.setWxMpConfigStorage(wxStorage);

		// 创建模板信息
		WxMpTemplateMessage templateMessage = WxMpTemplateMessage.builder()
				.toUser(wechatId)
				.templateId(templateId)
				.build();
		// 获取天气预报信息
		BaiduWeatherParam baiduWeatherParam = BaiduWeatherParam.builder()
				.district_id(userInfo.getDistrictId())
				.data_type("all")
				.ak(this.ak)
				.build();
		String queryWeather = baiduWeatherRemoteClient.queryWeather(baiduWeatherParam);
		log.info("查询的百度天气信息为：{}",queryWeather);
		BaiduNowWeather baiduNowWeather = ApiResponse.parseBaiduNowData(queryWeather, BaiduNowWeather.class);
		List<BaiduForecastsWeather> baiduForecastsWeatherList = ApiResponse.parseBaiduForecastsData(queryWeather, BaiduForecastsWeather.class);
		log.info("baiduNowWeather:{},baiduForecastsWeather:{}",baiduNowWeather,baiduForecastsWeatherList);
		// 获取彩虹屁
		TianXinParam tianXinParam = TianXinParam.builder().key(this.key).build();
		String queryRainbow = tianDataRemoteClient.queryRainbow(tianXinParam);
		List<TianRainbow> rainbowList = ApiResponse.parseTianData(queryRainbow, TianRainbow.class);

		// 获取每日一句
		String queryEnsentence = tianDataRemoteClient.queryEnsentence(tianXinParam);
		List<TianEnsentence> tianEnsentenceList = ApiResponse.parseTianData(queryEnsentence, TianEnsentence.class);

		// 封装模板数据
		templateMessage.addData(new WxMpTemplateData("now", this.pareDateNow(baiduForecastsWeatherList.get(0)),"#FFB6C1"));
		templateMessage.addData(new WxMpTemplateData("city",userInfo.getCity(),"#B95EA6"));
		templateMessage.addData(new WxMpTemplateData("text",baiduNowWeather.getText(),"#173177"));
		templateMessage.addData(new WxMpTemplateData("high",baiduForecastsWeatherList.get(0).getHigh(),"#87cefa"));
		templateMessage.addData(new WxMpTemplateData("low",baiduForecastsWeatherList.get(0).getLow(),"#FF6347"));
		templateMessage.addData(new WxMpTemplateData("scq_day",this.calScqDate(userInfo),"#FF1493"));
		templateMessage.addData(new WxMpTemplateData("bir_day",this.calBirData(userInfo),"#FF00FF" ));
		templateMessage.addData(new WxMpTemplateData("daily_english_cn",rainbowList.get(0).getContent(),"#800080"));
		templateMessage.addData(new WxMpTemplateData("daily_english_en",tianEnsentenceList.get(0).getEn(),"#FFA500"));

		log.info("发送的消息为：{}", JSON.toJSONString(templateMessage));
		wxMpService.getTemplateMsgService().sendTemplateMsg(templateMessage);
	}

	/**
	 * 计算想认识/想恋日期
	 * @return
	 */
	private String calScqDate(UserInfo userInfo){
		// 获取第一次想认识的时间
		if (Objects.nonNull(userInfo)){
			Date scqTime = userInfo.getScqTime();
			// 计算时间差
			long between = DateUtil.between(scqTime, DateUtil.date(), DateUnit.DAY);
			return String.valueOf(between);
		}
		return "";
	}

	/**
	 * 计算生日
	 * @param userInfo
	 * @return
	 */
	private String calBirData(UserInfo userInfo){
		// 获取用户的出生日期
		if (Objects.nonNull(userInfo)){
			Date birTime = userInfo.getBirTime();
			// 今日日期
			Calendar today = Calendar.getInstance();
			// 出生日期
			Calendar birthDay = Calendar.getInstance();
			// 设置生日
			birthDay.setTime(birTime);
			// 修改为本年
			int bir;
			birthDay.set(Calendar.YEAR,today.get(Calendar.YEAR));
			if (birthDay.get(Calendar.DAY_OF_YEAR) < today.get(Calendar.DAY_OF_YEAR)){
				// 生日已经过了，计算明年的
				bir = today.getActualMaximum(Calendar.DAY_OF_YEAR) - today.get(Calendar.DAY_OF_YEAR);
				bir += birthDay.get(Calendar.DAY_OF_YEAR);
			} else {
				// 生日还没过
				bir = birthDay.get(Calendar.DAY_OF_YEAR) - today.get(Calendar.DAY_OF_YEAR);
			}
			return String.valueOf(bir);
		}
		return "";
	}


	/**
	 * 拼接今日时间
	 * @return
	 */
	private String pareDateNow(BaiduForecastsWeather baiduForecastsWeather){
		// 获取当前日期
		String now =  DateUtil.format(DateUtil.date(), DatePattern.CHINESE_DATE_PATTERN);
		// 获取星期几
		String week = baiduForecastsWeather.getWeek();
		return now+" "+week;
	}
}
